<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { IconifyIcon } from '@vben/icons';

import { message } from 'ant-design-vue';

import {
  getMarketCategories,
  getMarketListings,
  getMarketStats,
} from '#/api/resource-center';

const router = useRouter();

// 响应式数据
const loading = ref(false);
const showCreateModal = ref(false);
const viewMode = ref('grid');
const activeQuickFilter = ref('');

// 统计数据
const stats = ref({
  overview: {
    totalListings: 0,
    activeListings: 0,
    totalOrders: 0,
    completedOrders: 0,
    totalTransactionValue: 0,
    totalUsers: 0,
    activeUsers: 0,
  },
});

// 搜索表单
const searchForm = reactive({
  keyword: '',
  category: undefined,
  resourceType: undefined,
  businessType: undefined,
  minPrice: undefined,
  maxPrice: undefined,
  sortBy: 'createdAt',
  sortOrder: 'desc',
  isHot: undefined,
  isNew: undefined,
});

// 快速筛选选项
const quickFilters = [
  { key: '', label: '全部' },
  { key: 'hot', label: '热门推荐' },
  { key: 'new', label: '最新上架' },
  { key: 'hotel', label: '酒店资源' },
  { key: 'restaurant', label: '餐饮资源' },
  { key: 'software', label: '软件服务' },
  { key: 'service', label: '人力服务' },
];

// 分类数据
const categories = ref([]);

// 资源列表
const listings = ref([]);

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 12,
  total: 0,
});

// 格式化价格
const formatPrice = (price: number) => {
  if (price >= 10_000) {
    return `${(price / 10_000).toFixed(1)}万`;
  }
  return price.toLocaleString();
};

// 加载市场统计
const loadMarketStats = async () => {
  try {
    const result = await getMarketStats();
    stats.value = result;
  } catch (error) {
    console.error('获取市场统计失败:', error);
    message.error('获取市场统计失败');
  }
};

// 加载分类
const loadCategories = async () => {
  try {
    const result = await getMarketCategories();
    categories.value = result;
  } catch (error) {
    console.error('获取分类失败:', error);
  }
};

// 加载资源列表
const loadListings = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm,
      page: pagination.current,
      pageSize: pagination.pageSize,
    };

    const result = await getMarketListings(params);
    listings.value = result.items || [];
    pagination.total = result.total || 0;
  } catch (error) {
    console.error('获取资源列表失败:', error);
    message.error('获取资源列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.current = 1;
  loadListings();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    category: undefined,
    resourceType: undefined,
    businessType: undefined,
    minPrice: undefined,
    maxPrice: undefined,
    sortBy: 'createdAt',
    sortOrder: 'desc',
    isHot: undefined,
    isNew: undefined,
  });
  activeQuickFilter.value = '';
  pagination.current = 1;
  loadListings();
};

// 快速筛选
const handleQuickFilter = (filterKey: string) => {
  activeQuickFilter.value = filterKey;

  // 重置搜索条件
  Object.assign(searchForm, {
    keyword: '',
    category: undefined,
    resourceType: undefined,
    businessType: undefined,
    minPrice: undefined,
    maxPrice: undefined,
    isHot: undefined,
    isNew: undefined,
  });

  // 设置对应的筛选条件
  switch (filterKey) {
    case 'hot': {
      searchForm.isHot = 'true';
      break;
    }
    case 'hotel':
    case 'restaurant':
    case 'service':
    case 'software': {
      searchForm.category = filterKey;
      break;
    }
    case 'new': {
      searchForm.isNew = 'true';
      break;
    }
  }

  pagination.current = 1;
  loadListings();
};

// 视图模式切换
const handleViewModeChange = () => {
  // 可以在这里保存用户偏好
};

// 分页处理
const handlePageChange = (page: number) => {
  pagination.current = page;
  loadListings();
};

const handlePageSizeChange = (current: number, size: number) => {
  pagination.current = current;
  pagination.pageSize = size;
  loadListings();
};

// 查看详情
const viewListingDetail = (id: string) => {
  // 跳转到详情页或者打开详情弹窗
  console.log('查看详情:', id);
  // router.push(`/resource-center/market/listing/${id}`);
};

// 收藏操作
const favoriteAction = (listing: any) => {
  console.log('收藏操作:', listing.id);
  message.success('收藏成功');
};

// 分享操作
const shareAction = (listing: any) => {
  console.log('分享操作:', listing.id);
  message.success('分享链接已复制');
};

// 立即购买
const buyNow = (listing: any) => {
  console.log('立即购买:', listing.id);
  router.push('/resource-center/market/orders');
};

// 初始化
onMounted(async () => {
  await Promise.all([loadMarketStats(), loadCategories(), loadListings()]);
});
</script>

<template>
  <div class="market-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <a-row :gutter="24" align="middle">
        <a-col flex="1">
          <h2>资源市场</h2>
          <p class="page-description">发现和交易各类优质资源</p>
        </a-col>
        <a-col>
          <a-space>
            <a-button type="primary" @click="showCreateModal = true">
              <template #icon>
                <IconifyIcon icon="ant-design:plus-outlined" />
              </template>
              发布资源
            </a-button>
            <a-button @click="loadMarketStats">
              <template #icon><SyncOutlined /></template>
              刷新
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>

    <!-- 统计卡片 -->
    <a-row :gutter="16" class="stats-row">
      <a-col :span="6">
        <a-card size="small">
          <a-statistic
            title="在售资源"
            :value="stats.overview.activeListings"
            :value-style="{ color: '#3f8600' }"
          >
            <template #prefix><ShopOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card size="small">
          <a-statistic
            title="总交易额"
            :value="stats.overview.totalTransactionValue"
            :precision="0"
            suffix="元"
            :value-style="{ color: '#cf1322' }"
          >
            <template #prefix><MoneyCollectOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card size="small">
          <a-statistic
            title="已完成订单"
            :value="stats.overview.completedOrders"
            :value-style="{ color: '#1890ff' }"
          >
            <template #prefix><CheckCircleOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card size="small">
          <a-statistic
            title="活跃用户"
            :value="stats.overview.activeUsers"
            :value-style="{ color: '#722ed1' }"
          >
            <template #prefix><UserOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 搜索和筛选 -->
    <a-card class="search-card" size="small">
      <a-form :model="searchForm" layout="inline" @finish="handleSearch">
        <a-form-item label="关键词" name="keyword">
          <a-input
            v-model="searchForm.keyword"
            placeholder="搜索资源名称、描述"
            allow-clear
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item label="分类" name="category">
          <a-select
            v-model="searchForm.category"
            placeholder="选择分类"
            allow-clear
            style="width: 150px"
          >
            <a-select-option
              v-for="category in categories"
              :key="category.id"
              :value="category.id"
            >
              {{ category.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="资源类型" name="resourceType">
          <a-select
            v-model="searchForm.resourceType"
            placeholder="选择类型"
            allow-clear
            style="width: 150px"
          >
            <a-select-option value="PHYSICAL">物理资源</a-select-option>
            <a-select-option value="DIGITAL">数字资源</a-select-option>
            <a-select-option value="HUMAN">人力资源</a-select-option>
            <a-select-option value="SERVICE">服务资源</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="价格范围" name="priceRange">
          <a-input-number
            v-model="searchForm.minPrice"
            placeholder="最低价"
            style="width: 100px"
          />
          <span style="margin: 0 8px">-</span>
          <a-input-number
            v-model="searchForm.maxPrice"
            placeholder="最高价"
            style="width: 100px"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">
            <template #icon><SearchOutlined /></template>
            搜索
          </a-button>
        </a-form-item>
        <a-form-item>
          <a-button @click="resetSearch">重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 快速筛选标签 -->
    <div class="quick-filters">
      <a-space wrap>
        <a-tag
          v-for="filter in quickFilters"
          :key="filter.key"
          :color="activeQuickFilter === filter.key ? 'blue' : ''"
          class="quick-filter-tag"
          @click="handleQuickFilter(filter.key)"
        >
          {{ filter.label }}
        </a-tag>
      </a-space>
    </div>

    <!-- 排序和视图切换 -->
    <div class="toolbar">
      <a-row justify="space-between" align="middle">
        <a-col>
          <a-space>
            <span>排序方式：</span>
            <a-select
              v-model="searchForm.sortBy"
              style="width: 120px"
              @change="loadListings"
            >
              <a-select-option value="createdAt">最新发布</a-select-option>
              <a-select-option value="price">价格</a-select-option>
              <a-select-option value="rating">评分</a-select-option>
              <a-select-option value="views">浏览量</a-select-option>
              <a-select-option value="favorites">收藏数</a-select-option>
            </a-select>
            <a-select
              v-model="searchForm.sortOrder"
              style="width: 80px"
              @change="loadListings"
            >
              <a-select-option value="desc">降序</a-select-option>
              <a-select-option value="asc">升序</a-select-option>
            </a-select>
          </a-space>
        </a-col>
        <a-col>
          <a-space>
            <span>视图：</span>
            <a-radio-group v-model="viewMode" @change="handleViewModeChange">
              <a-radio-button value="grid">网格</a-radio-button>
              <a-radio-button value="list">列表</a-radio-button>
            </a-radio-group>
          </a-space>
        </a-col>
      </a-row>
    </div>

    <!-- 资源列表 -->
    <a-spin :spinning="loading">
      <!-- 网格视图 -->
      <div v-if="viewMode === 'grid'" class="grid-view">
        <a-row :gutter="[16, 16]">
          <a-col
            v-for="listing in listings"
            :key="listing.id"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
          >
            <a-card
              hoverable
              class="listing-card"
              @click="viewListingDetail(listing.id)"
            >
              <template #cover>
                <div class="card-cover">
                  <img
                    :alt="listing.title"
                    :src="listing.images[0] || '/images/placeholder.jpg'"
                    class="cover-image"
                  />
                  <div class="card-overlay">
                    <a-space>
                      <a-button
                        type="link"
                        size="small"
                        @click.stop="favoriteAction(listing)"
                      >
                        <HeartOutlined v-if="!listing.isFavorited" />
                        <HeartFilled v-else style="color: #f5222d" />
                      </a-button>
                      <a-button
                        type="link"
                        size="small"
                        @click.stop="shareAction(listing)"
                      >
                        <IconifyIcon icon="ant-design:share-alt-outlined" />
                      </a-button>
                    </a-space>
                  </div>
                  <!-- 标签 -->
                  <div class="card-badges">
                    <a-tag v-if="listing.isHot" color="red" size="small">
                      热门
                    </a-tag>
                    <a-tag v-if="listing.isNew" color="green" size="small">
                      新品
                    </a-tag>
                  </div>
                </div>
              </template>
              <template #actions>
                <a-button
                  type="primary"
                  size="small"
                  block
                  @click.stop="buyNow(listing)"
                >
                  立即购买
                </a-button>
              </template>
              <a-card-meta
                :title="listing.title"
                :description="`${listing.description.slice(0, 50)}...`"
              />
              <div class="card-content">
                <div class="price-info">
                  <span class="current-price">
                    ¥{{ formatPrice(listing.price.currentPrice) }}
                  </span>
                  <span
                    v-if="listing.price.discount > 0"
                    class="original-price"
                  >
                    ¥{{ formatPrice(listing.price.basePrice) }}
                  </span>
                  <span class="price-unit">{{ listing.price.unit }}</span>
                </div>
                <div class="seller-info">
                  <a-space size="small">
                    <a-avatar :size="20" :src="listing.seller.avatar" />
                    <span class="seller-name">{{ listing.seller.name }}</span>
                    <a-rate
                      :value="listing.seller.rating"
                      :count="5"
                      disabled
                      allow-half
                      style="font-size: 12px"
                    />
                  </a-space>
                </div>
                <div class="listing-stats">
                  <a-space>
                    <span><IconifyIcon icon="ant-design:eye-outlined" />
                      {{ listing.views }}</span>
                    <span><HeartOutlined /> {{ listing.favorites }}</span>
                    <span><StarOutlined /> {{ listing.ratings.average }}</span>
                  </a-space>
                </div>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 列表视图 -->
      <div v-else class="list-view">
        <a-list
          :data-source="listings"
          item-layout="vertical"
          size="large"
          :pagination="false"
        >
          <template #renderItem="{ item }">
            <a-list-item
              class="listing-item"
              @click="viewListingDetail(item.id)"
            >
              <template #actions>
                <a-space>
                  <a-button size="small" @click.stop="favoriteAction(item)">
                    <HeartOutlined v-if="!item.isFavorited" />
                    <HeartFilled v-else style="color: #f5222d" />
                    {{ item.favorites }}
                  </a-button>
                  <a-button size="small" @click.stop="shareAction(item)">
                    <IconifyIcon icon="ant-design:share-alt-outlined" />
                  </a-button>
                  <a-button
                    type="primary"
                    size="small"
                    @click.stop="buyNow(item)"
                  >
                    立即购买
                  </a-button>
                </a-space>
              </template>
              <template #extra>
                <img
                  width="272"
                  height="200"
                  alt="logo"
                  :src="item.images[0] || '/images/placeholder.jpg'"
                  class="list-image"
                />
              </template>
              <a-list-item-meta
                :title="item.title"
                :description="item.description"
              >
                <template #avatar>
                  <a-avatar :src="item.seller.avatar" />
                </template>
              </a-list-item-meta>
              <div class="list-content">
                <div class="price-section">
                  <span class="current-price">
                    ¥{{ formatPrice(item.price.currentPrice) }}
                  </span>
                  <span v-if="item.price.discount > 0" class="original-price">
                    ¥{{ formatPrice(item.price.basePrice) }}
                  </span>
                  <span class="price-unit">{{ item.price.unit }}</span>
                  <a-tag v-if="item.price.negotiable" color="blue" size="small">
                    可议价
                  </a-tag>
                </div>
                <div class="tags-section">
                  <a-tag
                    v-for="tag in item.tags.slice(0, 3)"
                    :key="tag"
                    size="small"
                  >
                    {{ tag }}
                  </a-tag>
                  <a-tag v-if="item.isHot" color="red" size="small">热门</a-tag>
                  <a-tag v-if="item.isNew" color="green" size="small">
                    新品
                  </a-tag>
                </div>
                <div class="stats-section">
                  <a-space>
                    <span><IconifyIcon icon="ant-design:eye-outlined" />
                      {{ item.views }} 浏览</span>
                    <span><HeartOutlined /> {{ item.favorites }} 收藏</span>
                    <span>
                      <StarOutlined />
                      {{ item.ratings.average }} ({{ item.ratings.total }}评价)
                    </span>
                    <span>
                      <UserOutlined />
                      {{ item.seller.name }}
                      <a-rate
                        :value="item.seller.rating"
                        :count="5"
                        disabled
                        allow-half
                        style="margin-left: 4px; font-size: 12px"
                      />
                    </span>
                  </a-space>
                </div>
              </div>
            </a-list-item>
          </template>
        </a-list>
      </div>
    </a-spin>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <a-pagination
        v-model:current="pagination.current"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :show-size-changer="true"
        :show-quick-jumper="true"
        :show-total="
          (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
        "
        @change="handlePageChange"
        @show-size-change="handlePageSizeChange"
      />
    </div>

    <!-- 发布资源弹窗 -->
    <a-modal
      v-model:visible="showCreateModal"
      title="发布资源"
      width="800px"
      :footer="null"
    >
      <p>发布资源功能开发中...</p>
    </a-modal>
  </div>
</template>

<style scoped>
.market-page {
  padding: 16px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.page-description {
  margin: 4px 0 0;
  font-size: 14px;
  color: #6b7280;
}

.stats-row {
  margin-bottom: 24px;
}

.search-card {
  margin-bottom: 16px;
}

.quick-filters {
  margin-bottom: 16px;
}

.quick-filter-tag {
  cursor: pointer;
  transition: all 0.2s;
}

.quick-filter-tag:hover {
  transform: translateY(-1px);
}

.toolbar {
  padding: 12px 16px;
  margin-bottom: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.grid-view .listing-card {
  overflow: hidden;
  border-radius: 8px;
  transition: all 0.3s;
}

.grid-view .listing-card:hover {
  box-shadow: 0 4px 12px rgb(0 0 0 / 10%);
  transform: translateY(-2px);
}

.card-cover {
  position: relative;
}

.cover-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.card-overlay {
  position: absolute;
  top: 8px;
  right: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.listing-card:hover .card-overlay {
  opacity: 1;
}

.card-badges {
  position: absolute;
  top: 8px;
  left: 8px;
}

.card-content {
  padding: 8px 0;
}

.price-info {
  margin-bottom: 8px;
}

.current-price {
  font-size: 18px;
  font-weight: 600;
  color: #f5222d;
}

.original-price {
  margin-left: 8px;
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.price-unit {
  margin-left: 4px;
  font-size: 12px;
  color: #666;
}

.seller-info {
  margin-bottom: 8px;
}

.seller-name {
  font-size: 12px;
  color: #666;
}

.listing-stats {
  font-size: 12px;
  color: #999;
}

.list-view .listing-item {
  padding: 16px;
  margin-bottom: 16px;
  cursor: pointer;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  transition: all 0.3s;
}

.list-view .listing-item:hover {
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.list-image {
  object-fit: cover;
  border-radius: 8px;
}

.list-content {
  margin-top: 12px;
}

.price-section {
  margin-bottom: 8px;
}

.price-section .current-price {
  font-size: 20px;
  font-weight: 600;
  color: #f5222d;
}

.price-section .original-price {
  margin-left: 8px;
  font-size: 16px;
  color: #999;
  text-decoration: line-through;
}

.price-section .price-unit {
  margin-left: 4px;
  font-size: 14px;
  color: #666;
}

.tags-section {
  margin-bottom: 8px;
}

.stats-section {
  font-size: 14px;
  color: #666;
}

.pagination-wrapper {
  margin-top: 24px;
  text-align: center;
}
</style>
